package com.woniuxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.commons.exception.UserException;
import com.woniuxy.commons.exception.code.UserExceptionCode;
import com.woniuxy.commons.utils.BeanCopyUtil;
import com.woniuxy.commons.utils.CommonsUtil;
import com.woniuxy.commons.utils.WebUtil;
import com.woniuxy.controller.form.AccountRegisterForm;
import com.woniuxy.controller.form.MyStoreRegisterForm;
import com.woniuxy.dao.model.*;
import com.woniuxy.dao.AccountInfoDao;
import com.woniuxy.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.service.dto.CodeDto;
import com.woniuxy.service.dto.RegisterDto;
import com.woniuxy.service.dto.UserDetailsDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author psy
 * @since 2022-06-28
 */
@Service
public class AccountInfoServiceImpl extends ServiceImpl<AccountInfoDao, AccountInfo> implements AccountInfoService, UserDetailsService {
    @Resource
    private AccountInfoService accountInfoService;
    @Autowired
    private StoreInfoService storeInfoService;

    @Autowired
    private CustomerInfoService customerInfoService;

    @Autowired
    private RoleInfoService roleInfoService;

    @Autowired
    private AccountRoleService accountRoleService;

    @Autowired
    private StringRedisTemplate srt;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        AccountInfo accountInfo = this.getOne(new QueryWrapper<AccountInfo>().eq("accountName", username));

        if(accountInfo != null){
            UserDetailsDto ud = new UserDetailsDto();
            ud.setUsername(accountInfo.getAccountName());
            ud.setAccountId(accountInfo.getAccountId());
            ud.setPassword(accountInfo.getAccountPassword());
            if(accountInfo.getAccountType() == 1){
                StoreInfo storeInfo = storeInfoService.getOne(new QueryWrapper<StoreInfo>().eq("accountId", accountInfo.getAccountId()));
                ud.setId(storeInfo.getId());
                ud.setUsername(storeInfo.getStoreName());
                ud.setPhone(storeInfo.getPhone());
            }else if(accountInfo.getAccountType() == 2){
                CustomerInfo customerInfo = customerInfoService.getOne(new QueryWrapper<CustomerInfo>().eq("accountId", accountInfo.getAccountId()));
                ud.setId(customerInfo.getId());
                ud.setUsername(customerInfo.getCustomerName());
                ud.setPhone(customerInfo.getPhone());
            }
            return ud;
        }else throw new UsernameNotFoundException("用户不存在");

    }

    @Override
    public RegisterDto accountRegister(AccountRegisterForm accountRegisterForm) {
        //用户信息校验
        if (accountRegisterForm.getAccountName() == null || accountRegisterForm.getAccountName().equals("")) {
            throw new UserException(UserExceptionCode.USER_NOT_AccountName);
        }
        if (accountRegisterForm.getAccountPassword() == null || accountRegisterForm.getAccountPassword().equals("")) {
            throw new UserException(UserExceptionCode.USER_NOT_AccountPassword);
        }
        if (accountRegisterForm.getAccountPhone() == null || accountRegisterForm.getAccountPhone().equals("")) {
            throw new UserException(UserExceptionCode.USER_NOT_AccountPhone);
        }
        if (accountRegisterForm.getCode() == null || accountRegisterForm.getCode().equals("")) {
            throw new UserException(UserExceptionCode.USER_CODE_EXITS);
        }
        AccountInfo accountName = accountInfoService.getOne(new QueryWrapper<AccountInfo>().eq("accountName", accountRegisterForm.getAccountName()));
        if(null!=accountName){
            throw new UserException(UserExceptionCode.USER_HAS_REGISTER.getCode(),UserExceptionCode.USER_HAS_REGISTER.getMessage());
        }
        AccountInfo accountPhone = accountInfoService.getOne(new QueryWrapper<AccountInfo>().eq("accountPhone", accountRegisterForm.getAccountPhone()));
        if(null!=accountPhone){
            throw new UserException(UserExceptionCode.USER_HAS_REGISTER.getCode(),UserExceptionCode.USER_HAS_REGISTER.getMessage());
        }
        //获取redis中的验证码
        String s = srt.opsForValue().get("login:phone:code"+accountRegisterForm.getAccountPhone());
        if("".equals(s)||null==s){
            throw new UserException(UserExceptionCode.USER_CODE_NOT_EXITS.getCode(),UserExceptionCode.USER_CODE_NOT_EXITS.getMessage());
        }
//        CodeDto loginCode = (CodeDto) WebUtil.getRequest().getSession().getAttribute("login_code");
//        if (loginCode == null) throw new UserException(UserExceptionCode.USER_CODE_EXITS);
        if (!accountRegisterForm.getCode().equals(s))throw new UserException(UserExceptionCode.USER_CODE_WRONG);
        String s1 = CommonsUtil.BCrypt(accountRegisterForm.getAccountPassword());
        AccountInfo accountInfo = new AccountInfo(null, accountRegisterForm.getAccountName(), s1, 1, accountRegisterForm.getAccountPhone(), 2);
        save(accountInfo);
        AccountInfo account = accountInfoService.getOne(new QueryWrapper<AccountInfo>().eq("accountName", accountRegisterForm.getAccountName()));
        CustomerInfo customerInfo=new CustomerInfo();
        customerInfo.setAccountId(account.getAccountId());
        customerInfo.setCustomerName(account.getAccountName());
        customerInfo.setCustomerPhoto("https://woniu-75-3.oss-cn-chengdu.aliyuncs.com/img/a.jpg");
        customerInfo.setPhone(account.getAccountPhone());
        customerInfo.setStatus(1);
        boolean save = customerInfoService.save(customerInfo);
        return BeanCopyUtil.copyOne(accountInfo, RegisterDto.class);
    }

    @Override
    public boolean sendCode(String phone){

        StringBuffer code = new StringBuffer();
        Random random = new Random();
        for (int i =0;i<4;i++){
            code.append(random.nextInt(10));
        }

        Boolean b = srt.opsForValue().setIfAbsent("login:phone:code" + phone, code.toString(), 60, TimeUnit.SECONDS);

        if(!b) throw new UserException(UserExceptionCode.USER_CODE_EXITS);

        System.out.println("向"+phone+"发送了验证码"+code.toString());

        return true;

    }

    @Override
    public boolean storeAccountRegister(MyStoreRegisterForm myStoreRegisterForm) {

        AccountInfo accountInfo = new AccountInfo();
        accountInfo.setAccountName(myStoreRegisterForm.getUsername());
        accountInfo.setAccountPassword(CommonsUtil.BCrypt(myStoreRegisterForm.getPassword()));
        accountInfo.setAccountPhone(myStoreRegisterForm.getPhone());
        accountInfo.setAccountType(1);
        accountInfo.setAccountState(1);

        accountInfoService.save(accountInfo);

        AccountInfo account = accountInfoService.getOne(new QueryWrapper<AccountInfo>().eq("accountName", myStoreRegisterForm.getUsername()));

        StoreInfo storeInfo = new StoreInfo();

        storeInfo.setAccountId(account.getAccountId());

        storeInfo.setStoreName(account.getAccountName());

        storeInfo.setPhone(account.getAccountPhone());

        storeInfoService.save(storeInfo);

        RoleInfo role = roleInfoService.getById("3");
        String roleLevel = role.getRoleLevel();

        AccountRole accountRole = new AccountRole();
        accountRole.setRoleId(3);
        accountRole.setAccountId(account.getAccountId());
        accountRole.setRoleLevel(roleLevel);

        accountRoleService.save(accountRole);

        return true;
    }
}
